package jou.cs.service.impl;

import jou.cs.configurator.CONST;
import jou.cs.entity.TUser;
import jou.cs.mapper.UserRepository;
import jou.cs.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserImpl implements UserService {
    @Resource
    private UserRepository repository;

    @Override
    public void addUser(TUser user) {
        repository.save(user);
    }

    @Override
    public void deleteUser(Long id) {
        repository.deleteById(id);
    }

    @Override
    public void updateUser(TUser user) {
        repository.save(user);
    }

    @Override
    public Map<String, Object> getUserById(Long id) {
        TUser user = repository.findById(id).orElse(null);
        if (user == null)
            throw new RuntimeException("user not found");
        // user 转成map
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        return map;
    }

    @Override
    public Page<TUser> getUserByPage(int page) {
        return repository.findAll(PageRequest.of(page, CONST.PAGE_SIZE));
    }

    @Override
    public Long login(String username, String password) {
        TUser target = repository.findByAccountAndPassword(username, password);
        if (target == null)
            throw new RuntimeException("用户名或密码错误");
        // 用户喜欢

        // 用户问答
        // 用户点评
        return target.getId();
    }
}
